package com.wujian.love.service.impl;


import com.alibaba.fastjson.JSON;
import com.wujian.love.rocketmq.produce.TransactionProduce;
import com.wujian.love.domin.CustomerAccount;
import com.wujian.love.mapper.CustomerAccountMapper;
import com.wujian.love.service.PayService;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.common.message.Message;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @ClassName: PayServiceImpl
 * @description:
 * @author: wujian
 * @Date: 2020-06-11 15:25
 **/

@Service
public class PayServiceImpl implements PayService {

    private static final String TX_PAY_TOPIC = "tx_pay_topic";

    private static final String TX_PAY_TAGS = "tags";



    private CustomerAccountMapper customerAccountMapper;

    private TransactionProduce transactionProduce;


    @Override
    public String payment(String userId, String orderId, Integer accoundId, int money) {



        String paymentRet = "";
        try {
            //最开始有一个token(验证重复提单的问题)



            //查询出账户(小明)
            CustomerAccount old = customerAccountMapper.selectCustomerAccountById(accoundId);
            Integer currentBalance = old.getCurrentBalance();
            int version = old.getVersion();
            //技术出发
            //reids去重 分布式锁

            //乐观锁

            //业务出发
            //当前一个账号 只允许一个线程(一个应用端访问)


            Integer newBanlance = currentBalance - (money);
            if(newBanlance.doubleValue() > 0){  //获取一种情况获取锁也失败
                //组装消息
                //执行本地事务

                String keys = UUID.randomUUID().toString()+"$"+System.currentTimeMillis();
                Map<String,Object> map = new HashMap<>();
                map.put("userId",userId);
                map.put("orderId",orderId);
                map.put("accoundId",accoundId);
                map.put("money",money);
                Message message = new Message(TX_PAY_TOPIC,TX_PAY_TAGS,keys, JSON.toJSONString(map).getBytes());


                map.put("newBanlance",newBanlance);
                map.put("version",version);
                //消息发送,并且本地事务执行(并行操作)
                TransactionSendResult result = transactionProduce.sendMessage(message, map);

            }


        }catch (Exception e){

        }
















        return null;
    }
}
